package com.snail.snailvr.views.fragments;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;

import com.snail.snailvr.R;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.UpdateDownloadState;
import com.snail.snailvr.model.DownloadInfoChangeEvent;
import com.snail.snailvr.model.VideoInfo;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.JsonUrl;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.NetworkUtil;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.views.adapter.DownloadListAdapter;
import com.snail.snailvr.widget.HorizontalDividerItemDecoration;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.Subscription;

/**
 * 首页
 * Created by snail on 16/4/13.
 */
public class HomeFragment extends BaseDownloadFragment implements AdapterView.OnItemClickListener
        , View.OnClickListener, View.OnLongClickListener {
    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @Bind(R.id.empty_view)
    View mEmptyView;
    private Activity mContext;
    private List<VideoInfo> mVideoInfoList;
    private DownloadListAdapter mAdapter;
    private DownloadManager mDownloadManager;
    private Subscription mGetDownloadSubscription;

    @Subscribe
    public void onDownloadInfoChange(DownloadInfoChangeEvent event) {
        downloadInfoChange(event);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusProvider.getInstance().register(this);
    }

    @Override
    protected void handleIntent() {

    }

    @Override
    protected void initView() {
        mContext = getActivity();
        setupListView();
        setupDownload();
    }

    private void setupListView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mVideoInfoList = new ArrayList<>();
        mAdapter = new DownloadListAdapter(getActivity(), mVideoInfoList, this, this);
        mRecyclerView.setAdapter(mAdapter);
        addDivider();
    }
    protected void addDivider() {
        HorizontalDividerItemDecoration horizontalDividerItemDecoration=new HorizontalDividerItemDecoration.Builder(getActivity())
                .paintProvider(mAdapter)
                .visibilityProvider(mAdapter)
                .marginProvider(mAdapter)
                .build();
        horizontalDividerItemDecoration.setBackgroundPaintColor(getResources().getColor(R.color.list_item_color_normal));
        mRecyclerView.addItemDecoration(horizontalDividerItemDecoration);
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }


    private void setupDownload() {
        getDownloadList();
        setupDownloadManager();
        downloadDemoVideo();
    }


    private void setupDownloadManager() {
        mDownloadManager = DownloadHelper.getDownloadManager();
        mDownloadManager.setAccessAllDownloads(true);
    }

    /**
     * 首次进入下载Demo视频
     */
    private void downloadDemoVideo() {
        if (SharedPreferencesUtil.getInstance(getActivity()).getIsFirst() && NetworkUtil.isWifiConnected()) {
            DownloadHelper.startDownload(JsonUrl.DEMO_VIDEO_URL,true, Constant.STRING_DEMO);
            SharedPreferencesUtil.getInstance(getActivity()).setIsFirst(false);
        }
    }

    /**
     * 添加视频下载
     *
     * @param videoInfo
     */
    @Subscribe
    public void addNewVideoTask(VideoInfo videoInfo) {
        if (videoInfo != null) {
            resetVideoId(videoInfo);
            videoInfo.setDownloadBeginTime(System.currentTimeMillis());
            mVideoInfoList.add(0, videoInfo);
            //TODO 这里面有问题
            mAdapter.notifyItemInserted(mAdapter.getHeaderCount());
            hideEmptyView();
            videoInfo.save();
        }
    }

    private void showEmptyView(){
        if(mVideoInfoList.isEmpty()) {
            mEmptyView.setVisibility(View.VISIBLE);
            View headerView=mAdapter.getHeaderView();
            if(headerView!=null){
                headerView.findViewById(R.id.videos_below).setVisibility(View.GONE);
            }
        }
    }

    private void hideEmptyView(){
        if(mEmptyView.getVisibility()==View.VISIBLE) {
            mEmptyView.setVisibility(View.GONE);
            View headerView=mAdapter.getHeaderView();
            if(headerView!=null){
                headerView.findViewById(R.id.videos_below).setVisibility(View.VISIBLE);
            }
        }
    }
    /**
     * 如果此视频是通过网盘或者wifi传输过来的需要重新设置videoid用于排序
     * @param videoInfo videoinfo
     */
    private void resetVideoId(VideoInfo videoInfo) {

        if(!videoInfo.isDownloadByDownloadManager()){
            videoInfo.setVideoId(SharedPreferencesUtil.getInstance().getDownloadIdOutDownloadManager());
//            if(mVideoInfoList.isEmpty())
//                videoInfo.setVideoId(1);
//            else{
//                videoInfo.setVideoId(mVideoInfoList.get(0).getVideoId()+1);
//            }
        }
    }

    private void getDownloadList() {
        mGetDownloadSubscription = DatabaseUtils.getAllDownloads(new Subscriber<VideoInfo>() {
            @Override
            public void onCompleted() {
                if(mVideoInfoList.isEmpty())
                    showEmptyView();
                else {
                    mAdapter.notifyItemRangeInserted(mAdapter.getHeaderCount(), mVideoInfoList.size());
                }
                updateDownloadState();
            }

            @Override
            public void onError(Throwable e) {
                LogUtils.d("error="+e.getMessage());
            }

            @Override
            public void onNext(VideoInfo videoInfo) {
                mVideoInfoList.add(videoInfo);
            }
        });

    }




    /**
     * Send an Intent to open the download currently pointed to by the given
     * cursor.
     */
    private void openCurrentDownload(VideoInfo videoInfo) {
        try {
            IntentUtils.playVideo(getActivity(), videoInfo.getVideoPath(), videoInfo.getVideoName());
            removeNewTag(videoInfo);
        } catch (ActivityNotFoundException ex) {
            ToastUtils.makeToastColorShow(mContext, mRecyclerView, getResources().getString(R.string.download_no_application_title));
        }
    }

    /**
     * 去掉新视频的tag
     * @param videoInfo
     */
    private void removeNewTag(VideoInfo videoInfo) {
        videoInfo.setNewVideo(false);
        videoInfo.save();//更新数据库
        mAdapter.notifyItemChanged(mAdapter.getHeaderCount()+mVideoInfoList.indexOf(videoInfo));
    }

    private void handleItemClick(VideoInfo videoInfo) {
        int status = videoInfo.getDownloadState();
        switch (status) {
            case DownloadManager.STATUS_SUCCESSFUL:
                openCurrentDownload(videoInfo);
                break;
        }
    }


    /**
     * 长按列表对话框
     *
     * @param videoInfo
     */
    private void showLongClickDialog(final VideoInfo videoInfo) {
        DialogUtils.showBasicDialog(getActivity(), getString(R.string.delete), getString(R.string.dialog_delete_body)
                , getString(R.string.cancel), getString(R.string.string_delete), true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delete(videoInfo);
                    }
                });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        VideoInfo videoInfo = mAdapter.getItem(position);
        if (videoInfo != null)
            handleItemClick(videoInfo);
    }

    @Override
    public boolean onLongClick(View view) {
        VideoInfo videoInfo = (VideoInfo) view.getTag();
        if (videoInfo != null) {
            showLongClickDialog(videoInfo);
            return true;
        }
        return false;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_local_videos:
                IntentUtils.startAllVideoListActivity(getActivity());
                break;
            case R.id.download_list_item:
                handleItemClick((VideoInfo) v.getTag());
                break;
        }
    }

    /**
     * 删除选中列表数据
     *
     * @param videoInfo
     */
    private void delete(VideoInfo videoInfo) {
        if (videoInfo.getVideoId() != -1)
            mDownloadManager.remove(videoInfo.getVideoId());
        int position = mVideoInfoList.indexOf(videoInfo);
        LogUtils.d("delete videoid="+videoInfo.getVideoId());
        mVideoInfoList.remove(videoInfo);
        DatabaseUtils.deleteVideo(getActivity(),videoInfo);
        mAdapter.notifyItemRemoved(position+mAdapter.getHeaderCount());
        showEmptyView();
        DatabaseUtils.deleteVideo(getActivity(),videoInfo);
        BusProvider.getInstance().post(new UpdateDownloadState(videoInfo.getVideoId()));
    }



    @Override
    public void onStop() {
        super.onStop();
//        DatabaseUtils.saveDownloadList(mVideoInfoList);
    }

    @Override
    public void onDestroy() {

        if (mGetDownloadSubscription != null && !mGetDownloadSubscription.isUnsubscribed())
            mGetDownloadSubscription.unsubscribe();

        BusProvider.getInstance().unregister(this);
        super.onDestroy();
    }

    @Override
    protected RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    @Override
    protected RecyclerView.Adapter getAdapter() {
        return mAdapter;
    }

    @Override
    protected List<VideoInfo> getVideoInfoList() {
        return mVideoInfoList;
    }
}

